package com.example.qiandao.controller;

import com.example.qiandao.common.Result;
import com.example.qiandao.controller.requestdto.JoinClassRequestDTO;
import com.example.qiandao.controller.responsedto.ClassDTO;
import com.example.qiandao.entity.Clazz;
import com.example.qiandao.service.ClassService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/class")
public class ClassController {

    @Autowired
    private ClassService classService;

    /**
     * 根据课程ID查询该课程下所有班级的信息（包括班级名字和id）
     *
     * @param courseId 课程ID
     * @return 学生列表，包含学生名字和id
     */
    @GetMapping("/classlist/{courseId}")
    public Result<List<ClassDTO>> getClassesByCourseIdId(@PathVariable Long courseId) {
        List<ClassDTO> classes = classService.getClassesByCourseId(courseId);
        return Result.success(classes);
    }

    @PostMapping("/addclass")
    public Result<String> addClass(@RequestBody Clazz clazz) {
        boolean result = classService.addClass(clazz);
        return result ? Result.success("添加班级成功") : Result.error(400, "添加班级失败");
    }

    @PutMapping("/update")
    public Result<String> updateCourse(@RequestBody Clazz clazz) {
        boolean updated = classService.updateClass(clazz);
        if (updated) {
            return Result.success("课程更新成功");
        } else {
            return Result.error(400, "课程更新失败");
        }
    }

    @DeleteMapping("/delete/{classId}")
    public Result<String> deleteClass(@PathVariable Long classId) {
        boolean deleted = classService.deleteClass(classId);
        if (deleted) {
            return Result.success("班级删除成功");
        } else {
            return Result.error(400, "班级删除失败");
        }
    }


//--------------学生部分------------------------------------------------------------------------------------
    /**
     * 学生加入班级
     *
     * @param request 学生ID和班级码
     * @return 操作结果
     */
    @PostMapping("/join")
    public Result<String> joinClass(@RequestBody JoinClassRequestDTO request) {
        try {
            boolean result = classService.joinClass(request.getStudentId(), request.getClassCode());
            return result ? Result.success("加入班级成功") : Result.error(400, "加入班级失败");
        } catch (Exception e) {
            return Result.error(500, "服务器内部错误：" + e.getMessage());
        }
    }

    /**
     * 根据学生ID和课程ID获取学生在此课程下加入的所有班级
     *
     * @param studentId 学生ID
     * @param courseId 课程ID
     * @return 学生在此课程下加入的所有班级
     */
    @GetMapping("/classlist/{studentId}/{courseId}")
    public Result<List<ClassDTO>> getClassesByStudentIdAndCourseId(
            @PathVariable Long studentId,
            @PathVariable Long courseId) {
        List<ClassDTO> classes = classService.getClassesByStudentIdAndCourseId(studentId, courseId);
        return Result.success(classes);
    }
}